package com.sanpu.kxe.business.repay.presenter;

import android.app.Activity;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.sanpu.kxe.business.card.bean.BankInfoOutput;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.provider.IMainProvider;
import com.sanpu.kxe.business.repay.contract.RepayChannelContract;
import com.sanpu.kxe.business.trade.bean.PayCollectionOutput;
import com.sanpu.kxe.business.trade.contract.TradeConfig;
import com.sanpu.kxe.business.trade.provider.ITradeProvider;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.rxservice.RequestMap;
import com.sanpu.kxe.utils.DialogUtil;
import com.sanpu.kxe.utils.PublicProviderUtil;

import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：还款渠道
 * Created by 薛勇军 on 2019/4/24.
 */

public class RepayChannelPresenter implements RepayChannelContract.Presenter {

    private RepayChannelContract.View mView;

    private CompositeSubscription mSubscription;

    public RepayChannelPresenter(RepayChannelContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
        checkAuthenPass();
    }

    @Override
    public void onBindCard(String apprtId, BankInfoOutput infoOutput) {
        if (infoOutput == null || TextUtils.isEmpty(apprtId)) return;
        JSONObject reqData = new JSONObject();
        reqData.put("bankId", infoOutput.getBankId());
        reqData.put("apprtId", apprtId);
        reqData.put("billDay", infoOutput.getBillDay());
        reqData.put("dueDay", infoOutput.getDueDay());
        RequestMap requestMap = new RequestMap();
        requestMap.put(CommonConfig.REQDATA, new Gson().toJson(reqData));
        ITradeProvider provider = PublicProviderUtil.getProvider(ITradeProvider.class);
        if (provider != null) {
            provider.openQuickPayWebViewActivity(mView.getContext(),
                    UrlConstants.URL_BINDCARD, requestMap.map2ReqStr().replace("+", "%2B"));
        }
    }

    @Override
    public void appCnlConfList(String mercCardId) {
        mView.showLoadingDialog(false);
        ITradeProvider provider = PublicProviderUtil.getProvider(ITradeProvider.class);
        if (provider != null) {
            Subscription subscription = provider
                    .appCnlConfList(TradeConfig.RECEIVABLESTYPE_REPAY_CONSUME, mercCardId, "1.0.1")
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<PayCollectionOutput>>() {
                        @Override
                        public void onCompleted() {
                            mView.dismissLoadingDialog();
                        }

                        @Override
                        public void onError(Throwable e) {
                            mView.dismissLoadingDialog();
                            mView.showErrorText(e);
                            mView.showListDataView(null);
                        }

                        @Override
                        public void onNext(List<PayCollectionOutput> payCollectionOutputs) {
                            mView.showListDataView(payCollectionOutputs);
                        }
                    });
            mSubscription.add(subscription);
        }
    }

    /**
     * 验证认证状态
     */
    private void checkAuthenPass() {
        UserCenterOutput centerOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        final String mAuthenState = centerOutput.getChkSts();
        try {
            if (!TextUtils.equals(CommonConfig.AUTHEN_PASS, mAuthenState)) {
                String remark = null;
                if (TextUtils.equals(CommonConfig.AUTHEN_NOTSUB, mAuthenState)) {
                    remark = "请先进行实名认证，再代还";
                } else if (TextUtils.equals(CommonConfig.AUTHEN_AUDIT, mAuthenState)) {
                    remark = "实名认证正在审核中，请稍候";
                } else if (TextUtils.equals(CommonConfig.AUTHEN_NOPASS, mAuthenState)) {
                    remark = "实名认证审核失败，请重新提交审核通过后才能代还";
                } else if (TextUtils.equals(CommonConfig.AUTHEN_NOCOMPLETION, mAuthenState)) {
                    remark = "需要补全资料才能代还";
                }

                if (!TextUtils.isEmpty(remark)) {
                    DialogUtil.getInstance().dialogNoTitletTwoBtnHaveCallBack(mView.getContext(),
                            remark, "取消", "确定",
                            new DialogViewListener() {
                                @Override
                                public void btnRightConfirm() {
                                    if (!TextUtils.equals(CommonConfig.AUTHEN_AUDIT, mAuthenState)) {
                                        openCertificationActivity();
                                    }
                                    ((Activity)mView.getContext()).finish();
                                }

                                @Override
                                public void btnLeftCancel() {
                                    ((Activity)mView.getContext()).finish();
                                }
                            });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 实名认证
     */
    private void openCertificationActivity() {
        IMainProvider provider = PublicProviderUtil.getProvider(IMainProvider.class);
        if (provider != null) {
            provider.openCertificationActivity(mView.getContext(), true);
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
